package com.ibp.utils;


import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/***
 * 
 * http请求响应工具
 * @author yf141
 *
 */

public class HttpUtils {
	private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);	  
	//http客户端
	private static  CloseableHttpClient httpClient = null;
	
	/**
	 * get请求
	 * @param url
	 * @return
	 */
	public static String sendGetRequest(String url){
		httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		String response = sendRequest(httpGet);
		return response ;
	}
	
	/***
	 * post请求
	 * @param url
	 * @return
	 */
	public static String sendPostRequest(String url){
		httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		String response = sendRequest(httpPost);
		return response ;
	}
	
	/***
	 * 发送请求，并接收响应
	 * @param url
	 * @return
	 */
	public static String sendRequest(HttpRequestBase request){
		CloseableHttpResponse response = null ;
		try {
			response = (CloseableHttpResponse) httpClient.execute(request);
		    HttpEntity entity = response.getEntity();
		    String entityString = EntityUtils.toString(entity);
		    return entityString ;
		} catch (Exception e) {
			logger.error("http请求失败："+e);
		}finally{
			try {
				if(request!=null){
					request.releaseConnection();
				}
				if(response!= null){
					response.close();
				}
				if(httpClient != null ){
					httpClient.close();
				}
			} catch (IOException e) {
				logger.error("http关闭失败："+e);
			}
		}
		return null ;
	}
	
}
